package com.sl.hx.shop.http;


import com.sl.hx.shop.base.BaseFragmentView;
import com.sl.hx.shop.base.BaseView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by hwg on 2017/12/20.
 */

public class HttpUtil {

    /**
     * 私有化构造方法
     */
    private HttpUtil(){

    }

    /**
     * 在访问HttpUtil时创建单例
     */
    private static class SingletonHolder{
        private static final HttpUtil INSTANCE = new HttpUtil() ;
    }

    /**
     * 获取单例
     * @return
     */
    public static HttpUtil getInstance(){
        return SingletonHolder.INSTANCE ;
    }


    /**
     * 添加线程管理并订阅
     * activity中使用
     * @param ob
     * @param progressSubscribe
     * @param isShowProgress
     * @param mView
     * @param activityEvent
     */
    public void toSubscribe(Observable ob, final ProgressSubscribe progressSubscribe,
                            final boolean isShowProgress,
                            BaseView mView, ActivityEvent activityEvent){

        ObservableTransformer<HttpResult<Object>, Object> result = RxHelper.handleResult(mView, activityEvent) ;
        Observable observable = ob.compose(result)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (isShowProgress){
                            progressSubscribe.showProgressDialog();
                        }
                    }
                });

        observable.subscribe(progressSubscribe);
    }

    /**
     * 添加线程管理并订阅
     * fragment中使用
     * @param ob
     * @param progressSubscribe
     * @param isShowProgress
     * @param mView
     * @param fragmentEvent
     */
    public void toSubscribe(Observable ob, final ProgressSubscribe progressSubscribe,
                            final boolean isShowProgress, BaseFragmentView mView, FragmentEvent fragmentEvent){

        ObservableTransformer<HttpResult<Object>, Object> result = RxHelper.handleResult(mView, fragmentEvent) ;
        Observable observable = ob.compose(result)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (isShowProgress){
                            progressSubscribe.showProgressDialog();
                        }
                    }
                });

        observable.subscribe(progressSubscribe);

    }

}
